#include "content-handler.hh"

#include <cassert>

#include <fstream>

ContentHandler* ContentHandler::ch = 0;

ContentHandler*
ContentHandler::get (const std::string& transpath)
{
  if (!ch)
    ch = new ContentHandler (transpath);

  return ch;
}

ContentHandler::ContentHandler (const std::string& transpath):
  meshm_ ()
{
  std::ifstream ifs (transpath.c_str ());

  if (!ifs.is_open ())
  {
    std::cout << "ERROR couldn't open mesh<->object table, launch aborted" << std::endl;
    assert (0);
  }

  int id = -1;
  std::string tmp;
  std::string path = "content/";
  while (!ifs.eof ())
  {
    ifs >> tmp;
    id = atoi (tmp.c_str ());
    ifs >> tmp;
    meshm_.insert (std::make_pair (id, boost::shared_ptr<Mesh> (new Mesh (path + tmp))));
  }
}

void
ContentHandler::instantiate_mesh (int id, const std::string& filename)
{
  if (meshm_.find (id) != meshm_.end ())
  {
    std::cout << "error trying to instantiate 2 times mesh: " << filename << std::endl;
    assert (0);
  }

  meshm_.insert (std::make_pair (id, boost::shared_ptr<Mesh> (new Mesh (filename))));
}

void
ContentHandler::instantiate_texture (const std::string& id, const std::string& filename)
{
  if (texm_.find (id) != texm_.end ())
  {
    std::cout << "error trying to instantiate 2 times mesh: " << filename << std::endl;
    assert (0);
  }

  texm_.insert (std::make_pair (id, boost::shared_ptr<Texture> (new Texture (filename))));
}

boost::shared_ptr<Mesh>
ContentHandler::mesh (int id, Bounding* bounding, const Vector3f& pos, const Vector3d& rotate)
{
  boost::unordered_map<int, boost::shared_ptr<Mesh> >::iterator it = meshm_.find (id);

  if (it == meshm_.end ())
  {
    std::cout << "error mesh with id " << id << " not found in contenthandler map" << std::endl;
    assert (false);
  }

  return boost::shared_ptr<Mesh> (new Mesh (pos, rotate, bounding, it->second.get ()));
}

boost::shared_ptr<Texture>
ContentHandler::texture (const std::string& id)
{
  boost::unordered_map<std::string, boost::shared_ptr<Texture> >::iterator it = texm_.find (id);

  if (it == texm_.end ())
  {
    std::cout << "error texture with id " << id << " not found in contenthandler map" << std::endl;
    assert (false);
  }

  return it->second;
}
